package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.core.domain.PageQuery;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.utils.SecurityUtils;
import com.rla.common.utils.StringUtils;
import com.rla.domain.EhsEverydayBloodPressure;
import com.rla.domain.IntegralTask;
import com.rla.domain.PointsDetails;
import com.rla.domain.VipUserInfo;
import com.rla.domain.bo.VipUserInfoBo;
import com.rla.domain.vo.VipUserInfoVo;
import com.rla.mapper.IntegralTaskMapper;
import com.rla.mapper.PointsDetailsMapper;
import com.rla.mapper.VipUserInfoMapper;
import com.rla.service.IVipUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 小程序用户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-24
 */
@RequiredArgsConstructor
@Service
public class VipUserInfoServiceImpl implements IVipUserInfoService {

    private final VipUserInfoMapper baseMapper;

    private final PointsDetailsMapper pointsDetailsMapper;

    private final IntegralTaskMapper integralTaskMapper;
    /**
     * 查询小程序用户信息
     */
    @Override
    public VipUserInfoVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询小程序用户信息列表
     */
    @Override
    public TableDataInfo<VipUserInfoVo> queryPageList(VipUserInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<VipUserInfo> lqw = buildQueryWrapper(bo);
        Page<VipUserInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询小程序用户信息列表
     */
    @Override
    public List<VipUserInfoVo> queryList(VipUserInfoBo bo) {
        LambdaQueryWrapper<VipUserInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<VipUserInfo> buildQueryWrapper(VipUserInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<VipUserInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), VipUserInfo::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), VipUserInfo::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), VipUserInfo::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthday()), VipUserInfo::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), VipUserInfo::getIdCard, bo.getIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getHeight()), VipUserInfo::getHeight, bo.getHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getWeight()), VipUserInfo::getWeight, bo.getWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), VipUserInfo::getProvince, bo.getProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), VipUserInfo::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getCounty()), VipUserInfo::getCounty, bo.getCounty());
        lqw.eq(StringUtils.isNotBlank(bo.getRegion()), VipUserInfo::getRegion, bo.getRegion());
        lqw.eq(StringUtils.isNotBlank(bo.getAddressDetail()), VipUserInfo::getAddressDetail, bo.getAddressDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDiabetesType()), VipUserInfo::getDiabetesType, bo.getDiabetesType());
        lqw.eq(StringUtils.isNotBlank(bo.getDiagnosisDate()), VipUserInfo::getDiagnosisDate, bo.getDiagnosisDate());
        lqw.eq(StringUtils.isNotBlank(bo.getPastHistory()), VipUserInfo::getPastHistory, bo.getPastHistory());
        lqw.like(StringUtils.isNotBlank(bo.getEmergencyContactName()), VipUserInfo::getEmergencyContactName, bo.getEmergencyContactName());
        lqw.eq(StringUtils.isNotBlank(bo.getEmergencyContactPhone()), VipUserInfo::getEmergencyContactPhone, bo.getEmergencyContactPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getEmergencyContactCall()), VipUserInfo::getEmergencyContactCall, bo.getEmergencyContactCall());
        lqw.eq(bo.getSumIntegral() != null, VipUserInfo::getSumIntegral, bo.getSumIntegral());
        lqw.eq(bo.getUsableIntegral() != null, VipUserInfo::getUsableIntegral, bo.getUsableIntegral());
        lqw.eq(bo.getFreezeIntegral() != null, VipUserInfo::getFreezeIntegral, bo.getFreezeIntegral());
        lqw.eq(StringUtils.isNotBlank(bo.getVipGradeCode()), VipUserInfo::getVipGradeCode, bo.getVipGradeCode());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), VipUserInfo::getPassword, bo.getPassword());
        lqw.eq(bo.getSumBalance() != null, VipUserInfo::getSumBalance, bo.getSumBalance());
        lqw.eq(bo.getUsableBalance() != null, VipUserInfo::getUsableBalance, bo.getUsableBalance());
        lqw.eq(bo.getFreezeBalance() != null, VipUserInfo::getFreezeBalance, bo.getFreezeBalance());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginIp()), VipUserInfo::getLoginIp, bo.getLoginIp());
        lqw.eq(bo.getLoginDate() != null, VipUserInfo::getLoginDate, bo.getLoginDate());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), VipUserInfo::getOpenId, bo.getOpenId());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), VipUserInfo::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), VipUserInfo::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDpId()), VipUserInfo::getDpId, bo.getDpId());
        return lqw;
    }

    /**
     * 新增小程序用户信息
     */
    @Override
    public Boolean insertByBo(VipUserInfoBo bo) {
        VipUserInfo add = BeanUtil.toBean(bo, VipUserInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改小程序用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(VipUserInfoBo bo) {
        VipUserInfo update = BeanUtil.toBean(bo, VipUserInfo.class);
        validEntityBeforeSave(update);

        //去查看积分明细，如果存在任务已完成不添加积分，未完成添加积分并更改用户积分数量
        LambdaQueryWrapper<IntegralTask> lqw = Wrappers.lambdaQuery(IntegralTask.class)
                .eq(IntegralTask::getIsShow, "1");
        List<IntegralTask> integralTasks = integralTaskMapper.selectList(lqw);



        List<IntegralTask> list1 = integralTasks.stream().filter(item->item.getID()==13).collect(Collectors.toList());
        List<IntegralTask> list2 = integralTasks.stream().filter(item->item.getID()==14).collect(Collectors.toList());

        //个人资料完善
        if (CollectionUtil.isNotEmpty(list1)){
            LambdaQueryWrapper<PointsDetails> lqw1 = Wrappers.lambdaQuery(PointsDetails.class)
                    .eq(PointsDetails::getUserId, SecurityUtils.getUserId())
                    .eq(PointsDetails::getTaskId, 13L);
            List<PointsDetails> list = pointsDetailsMapper.selectList(lqw1);

            if (CollectionUtil.isEmpty(list)){
                VipUserInfoVo vipUserInfoVo = baseMapper.selectVoById(SecurityUtils.getUserId());
                PointsDetails pointsDetails = new PointsDetails();
                pointsDetails.setUserId(SecurityUtils.getUserId().toString());
                pointsDetails.setVariablePoints(list1.get(0).getRewardsPoints());
                pointsDetails.setOperator(SecurityUtils.getUserId().toString());
                pointsDetails.setChangeTime(new Date());
                pointsDetails.setChangeType("5");
                pointsDetails.setTask("个人资料完善");
                pointsDetails.setUserName(vipUserInfoVo.getUserName());
                pointsDetails.setPhone(vipUserInfoVo.getPhone());
                pointsDetails.setBeforePoints(vipUserInfoVo.getUsableIntegral());
                pointsDetails.setAfterPoints(vipUserInfoVo.getUsableIntegral()+list1.get(0).getRewardsPoints());
                update.setUsableIntegral(pointsDetails.getAfterPoints());
                pointsDetails.setTaskId(13L);
                pointsDetailsMapper.insert(pointsDetails);
                baseMapper.updateById(update);
            }
        }

        //病例信息
        if (CollectionUtil.isNotEmpty(list2)){
            LambdaQueryWrapper<PointsDetails> lqw1 = Wrappers.lambdaQuery(PointsDetails.class)
                    .eq(PointsDetails::getUserId, SecurityUtils.getUserId())
                    .eq(PointsDetails::getTaskId, 14L);
            List<PointsDetails> list = pointsDetailsMapper.selectList(lqw1);

            if (CollectionUtil.isEmpty(list)){
                VipUserInfoVo vipUserInfoVo = baseMapper.selectVoById(SecurityUtils.getUserId());
                PointsDetails pointsDetails = new PointsDetails();
                pointsDetails.setUserId(SecurityUtils.getUserId().toString());
                pointsDetails.setVariablePoints(list2.get(0).getRewardsPoints());
                pointsDetails.setOperator(SecurityUtils.getUserId().toString());
                pointsDetails.setChangeTime(new Date());
                pointsDetails.setChangeType("5");
                pointsDetails.setTask("病例信息");
                pointsDetails.setUserName(vipUserInfoVo.getUserName());
                pointsDetails.setPhone(vipUserInfoVo.getPhone());
                pointsDetails.setBeforePoints(vipUserInfoVo.getUsableIntegral());
                pointsDetails.setAfterPoints(vipUserInfoVo.getUsableIntegral()+list2.get(0).getRewardsPoints());
                pointsDetails.setTaskId(14L);
                update.setUsableIntegral(pointsDetails.getAfterPoints());
                pointsDetailsMapper.insert(pointsDetails);
                baseMapper.updateById(update);
            }
        }

        baseMapper.updateById(update);
        return  true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(VipUserInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除小程序用户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
